package com.iwinding.ladygg.ui.act;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bugtags.library.Bugtags;
import com.iwinding.ladygg.AppForegroundStateManager;
import com.iwinding.ladygg.ICaneApplication;
import com.iwinding.ladygg.R;
import com.iwinding.ladygg.bluetooth.impblekit.ICaneBleApi;
import com.iwinding.ladygg.ui.EasyPermissions;
import com.iwinding.ladygg.ui.view.ProDialogCreator;

import java.util.List;


/**
 * Created by Administrator on 2016/6/7.
 */
public abstract class BaseActivity extends Activity implements EasyPermissions.PermissionCallbacks {

    protected ICaneApplication mOAAplication;
    protected ImageView mBack;
    protected TextView mBackTxt;
    protected TextView mTitle;
    protected ImageView mRight;
    protected TextView mRightTxt;
    protected LinearLayout mContent;
    protected LinearLayout mHead;
    //    protected SwipeRefreshLayout swipeLayout;
    protected Activity mContext;


    protected ProgressDialog mProgress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if (this instanceof LoginActivity)
//            WindowUtil.fullScreenStatusBar(this, false);
//        else {
//            WindowUtil.bepaintStatusBar(this, getResources().getColor(R.color.colorBlue));
//        }

        setContentView(R.layout.icane_activity_base);
        mOAAplication = (ICaneApplication) getApplication();
        mContext = this;

        mHead = (LinearLayout) findViewById(R.id.base_head);
        mContent = (LinearLayout) findViewById(R.id.base_content);
        mBack = (ImageView) findViewById(R.id.base_head_back);
        mRight = (ImageView) findViewById(R.id.base_head_right);
        mTitle = (TextView) findViewById(R.id.base_head_title);
        mBackTxt = (TextView) findViewById(R.id.base_back_txt);
        mRightTxt = (TextView) findViewById(R.id.base_right_txt);
//        swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
//        swipeLayout.setOnRefreshListener(this);
//        swipeLayout.setColorSchemeColors(android.R.color.holo_blue_bright,
//                android.R.color.holo_green_light,
//                android.R.color.holo_orange_light,
//                android.R.color.holo_red_light);

        if (mBack != null) {
            mBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }

        View content = View.inflate(this, getLayoutID(), null);
        mContent.removeAllViews();
        content.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mContent.addView(content);
    }

    protected abstract int getLayoutID();


//    protected void setBackFunction(){
//
//    }

    protected void setHeadVisibility(int visibility) {
        mHead.setVisibility(visibility);
    }

    protected void setTitleStr(String title) {
        if (mTitle != null) {
            mTitle.setText(title);
        }
    }


    protected void setTitleResId(int resString) {
        if (mTitle != null) {
            mTitle.setText(getString(resString));
        }
    }

    protected void setBackTxtResId(int resString) {
        if (mBackTxt != null) {
            mBackTxt.setText(getString(resString));
//            mBackTxt.setVisibility(View.VISIBLE);
        }
    }

    protected void setBackTxtStr(String str) {
        if (mBackTxt != null) {
            mBackTxt.setText(str);
//            mBackTxt.setVisibility(View.VISIBLE);
        }
    }

    protected void setRightTxtResId(int resString) {
        if (mRightTxt != null) {
            mRightTxt.setText(getString(resString));
            mRightTxt.setVisibility(View.VISIBLE);
        }
    }

    protected void setmRightIcon(int resIcon) {
        if (mRight != null) {
            mRight.setImageResource(resIcon);
            mRight.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        ProDialogCreator.getInstance().initContext(this);
        ICaneBleApi.getInstance().initContext(this);
        Bugtags.onResume(this);
        if (mRight != null)
            mRight.setVisibility(mBack.getVisibility() != View.GONE ? View.INVISIBLE : View.GONE);
        AppForegroundStateManager.getInstance().onActivityVisible(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        AppForegroundStateManager.getInstance().onActivityNotVisible(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //注：回调 2
        Bugtags.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void loadingProgressDialog() {
        if (mProgress != null) {
            mProgress.dismiss();
            mProgress = null;
        }
        mProgress = new ProgressDialog(this);
        mProgress.show();
    }

//    public void loadingLoginDialog() {
//        if (mProgress != null) {
//            mProgress.dismiss();
//            mProgress = null;
//        }
//        mProgress = new ProgressDialog(this, ProgressDialog.Type.GIF);
//        mProgress.show();
//    }

    public void dismissProgressDialog() {
        mProgress.dismiss();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //注：回调 3
        Bugtags.onDispatchTouchEvent(this, ev);
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {

            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            View v = getCurrentFocus();

            if (isShouldHideInput(v, ev)) {
                hideSoftInput(v.getWindowToken());
            }
        }
        try {
            return super.dispatchTouchEvent(ev);
        } catch (Exception e) {

        }
        return false;
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 多种隐藏软件盘方法的其中一种
     *
     * @param token
     */
    public void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
    }

    protected void requiresPermission(String permissions[], String permissionsDesc, int requestCode) {
        // SDK 小于23默认已经授权
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            ActivityCompat.requestPermissions(this, permissions, requestCode);
        } else {
//            if (EasyPermissions.hasPermissions(mContext, permissions)) {
//                hasPermission();
//            } else {
            EasyPermissions.requestPermissions(mContext,
                    permissionsDesc, requestCode, permissions);
//            }
        }
    }
    protected boolean hasPermissions(Context context, String permissions[]) {
        return EasyPermissions.hasPermissions(context, permissions);
    }

    protected void hasPermission() {

    }

}
